<!--
 * @Descripttion: 表单组件
 * @Author: armin
 * @Date: 2021-07-19 11:49:18
 * @LastEditors: armin
 * @LastEditTime: 2021-07-19 14:49:01
-->
<template>
  <form class="validate-form-contanier">
    <slot></slot>
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button type="subimt" class="btn btn-primary">提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue'
import mitt from 'mitt'
// 实例化 mitt
type ValidateFunc = () => boolean

type ClearFunc = () => void
interface ICallbackProps {
  validator: ValidateFunc
  clearInput: ClearFunc
}
type Events = {
  'form-item-created': ICallbackProps
}
export const emitter = mitt<Events>()
export default defineComponent({
  emits: ['form-submit'],
  setup (props, ctx) {
    let funcArr: ValidateFunc[] = []
    let clearArr: ClearFunc[] = []
    const submitForm = () => {
      // 循环执行数组 得到最后的验证结果
      const result = funcArr.map(func => func()).every(result => result)
      ctx.emit('form-submit', result)
    }
    const callback = (obj?: ICallbackProps) => {
      if (obj) {
        funcArr.push(obj.validator)
        clearArr.push(obj.clearInput)
      }
    }
    const clearInputs = () => {
      clearArr.forEach(clear => clear())
    }
    // 添加监听
    emitter.on('form-item-created', callback)
    onUnmounted(() => {
      // 删除监听
      emitter.off('form-item-created', callback)
      funcArr = []
      clearArr = []
    })
    return {
      submitForm,
      clearInputs
    }
  }
})
</script>

<style scoped>
</style>
